package com.example.main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.toColorInt
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.navigation.NavHostController
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.base.app.RouterPath
import com.example.common.base.BaseActivity
import com.example.main.adapter.MainPageAdapter
import com.example.main.databinding.ActivityMainBinding
import com.example.main.tab.NormalTabView
import com.example.main.tab.RoundTabView
import dagger.hilt.android.AndroidEntryPoint
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener
import okhttp3.internal.http2.Settings

@AndroidEntryPoint
@Route(path = RouterPath.PATH_MAIN_ACTIVITY)
class MainActivity : BaseActivity<ActivityMainBinding>() {
    private lateinit var mNavController: NavigationController
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPageAdapter:MainPageAdapter
    override fun getLayoutId(): Int =R.layout.activity_main

    private var needUserPermission= arrayListOf(
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
    )
    private var unGrantPermission= arrayListOf<String>()

    private var hasUnGranted = false

    override fun initViews() {
        mNavController=mDataBinding.mainBottomNav.custom()
            .addItem(newCommonTabItem(R.drawable.ic_nor_home, R.drawable.ic_sel_home,"首页"))
            .addItem(newCommonTabItem(R.drawable.ic_nor_fang, R.drawable.ic_sel_fang,"放映厅"))
            .addItem(newRoundTabItem(R.drawable.ic_sel_add))
            .addItem(newCommonTabItem(R.drawable.ic_nor_zhi, R.drawable.ic_sel_zhi,"直播"))
            .addItem(newCommonTabItem(R.drawable.ic_nor_my, R.drawable.ic_sel_my,"我的"))
            .build()
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_HOME_PAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_MOVIE_PAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_LIVE_PAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_MINE_PAGE).navigation() as Fragment)
        mPageAdapter= MainPageAdapter(supportFragmentManager,fragments,FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT)
        mDataBinding.mainViewPager.apply {
            adapter = mPageAdapter
            offscreenPageLimit=3
        }
        mNavController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
            override fun onSelected(index: Int, old: Int) {
                when(index) {
                    0 ,1-> {
                        mDataBinding.mainViewPager.currentItem = index
                    }
                    2 -> {
                        ARouter.getInstance().build(RouterPath.PATH_PUBLISH_PAGE).navigation()
                        mNavController.setSelect(old)//恢复之前样式
                    }
                    3,4 -> {
                        mDataBinding.mainViewPager.currentItem = index-1
                    }
                }
            }

            override fun onRepeat(index: Int) {
                if (index ==2){
                    ARouter.getInstance().build(RouterPath.PATH_PUBLISH_PAGE).navigation()
                }
            }
        })
        mDataBinding.mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                when(position){
                    0,1->mNavController.setSelect(position)
                    2,3->mNavController.setSelect(position+1)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        //延时发起用户授权
        mDataBinding.mainViewPager.postDelayed({
            autoRequestPermission()
        },2000)
    }

    private fun autoRequestPermission() :   Boolean{
        //只有在安卓6.0以后才需要动态授权
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            //清理
            unGrantPermission.clear()
            //检查有哪些没有授权的权限
            needUserPermission.forEach {
                var state=checkSelfPermission(it)
                if (state==PackageManager.PERMISSION_DENIED){
                    unGrantPermission.add(it)
                }
            }
            //发起用户授权的请求
            if(unGrantPermission.size>0){
                requestPermissions(unGrantPermission.toTypedArray(),100)
                return false
            }
        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode==100 && Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            //检查未授权限是否被同意
            unGrantPermission.forEach {
                if (checkSelfPermission(it) ==PackageManager.PERMISSION_DENIED){
                    hasUnGranted=true
                }
            }
        }
        //如果有未授权的跳转到设置中心自己授权
        if (hasUnGranted){
            AlertDialog.Builder(this).apply {
                setTitle("权限展示")
                setMessage("您没有授权,请去设置中心授权")
                setPositiveButton("去设置"){dialog,which->
                    dialog.dismiss()
                    hasUnGranted=false
                    jumpToAppDetail()
                }
                setNegativeButton("取消") { dialog, which ->
                    dialog.dismiss()
                    hasUnGranted=false
                }
            }
        }
    }
    //跳转应用设置中心
    private fun jumpToAppDetail(){
        var intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this@MainActivity.startActivity(intent)
    }
    private fun newCommonTabItem(defaultIcon:Int,checkIcon:Int,title:String):BaseTabItem{
       return NormalTabView(this).apply {
           initData(defaultIcon, checkIcon, title)
           setDefaultTextColor(R.color.default_color)
           setCheckedTextColor(R.color.checked_color)
        }
    }
    private fun newRoundTabItem(defaultIcon:Int):BaseTabItem{
        return RoundTabView(this).apply {
            initData(defaultIcon)
        }
    }
}
